package club.beimeng.emailserver2.service.impl;

import club.beimeng.emailserver2.entity.EmailTemplate;
import club.beimeng.emailserver2.mapper.EmailTemplateMapper;
import club.beimeng.emailserver2.service.EmailTemplateService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 小艾同学
 * @since 2021-09-29
 */
@Service
public class EmailTemplateServiceImpl extends ServiceImpl<EmailTemplateMapper, EmailTemplate> implements EmailTemplateService {

    @Override
    public String getInnerHtml(String templateCode, Map<String,String> args) { // 通过templateId 和 参数列表 拼凑出完整的innerHtml
        // 通过templateCode 获取 html
        EmailTemplate template = this.getById(templateCode);

        if (template == null)
            throw new RuntimeException("未找到模板文件");

        String answerStr = template.getTemplate();

        // 替换所有变量值
        for (String s : args.keySet()) {
            answerStr = answerStr.replaceAll("\\$\\{" + s + "\\}",args.get(s));
        }

        return answerStr;
    }

    @Override
    public Long addTemplate(String template) {

        EmailTemplate emailTemplate = new EmailTemplate();
        emailTemplate.setTemplate(template);
        this.save(emailTemplate);
        System.out.println("emailTemplate = " + emailTemplate.getTid());

        return emailTemplate.getTid();
    }
}
